<?php

setlocale(LC_ALL, "ru_RU.UTF-8");
mb_internal_encoding("UTF-8");

$curRealDir = mb_substr($_SERVER["SCRIPT_FILENAME"], 0, mb_strrpos($_SERVER["SCRIPT_FILENAME"], "/"));

require_once ("./config/setup.php");
require_once ("./libs/db.class.php");
require_once ("./libs/utils.inc.php");
$sm = new SSmarty();
$db = new DB();

//--правый блок
//--из админки
$LAST_TAGS_COUNT = getOption($db, "LAST_TAGS_COUNT");
//-------------------

$db->dbq("
            Select
                tags
            From
                news
        ");
$lastTags = array();
while ($arr = $db->row()) {
    $tags = json_decode($arr[0], true);
    foreach ($tags as $key => $tag) {
        if ($tag != "") {
            if (!isset($lastTags[$tag])) {
                $query = preg_split("'
                                        [\ ,.\t\r\n]+
                                    'iusx", $tag);
                $utf8BytesRegexp = array();
                foreach ($query as $key => $value) {
                    $utf8BytesRegexp[] = mb_substr(json_encode($value), 1, mb_strlen(json_encode($value)) - 2);
                }
                $utf8BytesRegexp = implode("(.*)", $utf8BytesRegexp);
                $utf8BytesRegexp = addslashes(addslashes($utf8BytesRegexp));
                $regexp = implode("(.*)", $query);

                $db->dbqi(1, "
                            Select
                                Count(*)
                            From
                                news
                            Where
                                caption Regexp(\"" . $regexp . "\") ||
                                maintext Regexp(\"" . $regexp . "\") ||
                                DATE_FORMAT(postdate, \"%d %M %Y, %H:%i\") Regexp(\"" . $regexp . "\") ||
                                author Regexp(\"" . $regexp . "\") ||
                                tags Regexp(\"" . $utf8BytesRegexp . "\")
                        ");
                $arr = $db->rowi(1);
                $lastTags[$tag] = $arr[0];
            }
        }
    }
}

arsort($lastTags);
$lastTags = array_splice($lastTags, 0, $LAST_TAGS_COUNT);
$sm->assign("lastTags", $lastTags);

//------------------------------------

//---из админки
$NEWS_PER_PAGE = getOption($db, "NEWS_PER_PAGE");
$NEWS_MAX_LEN_PREVIEW = getOption($db, "NEWS_MAX_LEN_PREVIEW");
//-----------------------

$db->dbq("
            Select
                Count(*)
            From
                news
        ");
$arr = $db->row();
if ($arr[0] % $NEWS_PER_PAGE == 0) {
    $countPages = (int) ($arr[0] / $NEWS_PER_PAGE);
} else {
    $countPages = (int) ($arr[0] / $NEWS_PER_PAGE) + 1;
}
$sm->assign("countPages", $countPages);

$pagenum = trim(mysql_real_escape_string($_GET["pagenum"]));
if (!preg_match("'^[0-9]+$'iu", $pagenum) || $pagenum < 1 || $pagenum > $countPages) {
    $pagenum = 1;
}

//--создаем массивы индексов для счетчика
//---из админки
$NEWS_COUNTER_LEFT = getOption($db, "NEWS_COUNTER_LEFT");
$NEWS_COUNTER_CENTER = getOption($db, "NEWS_COUNTER_CENTER");
$NEWS_COUNTER_RIGHT = getOption($db, "NEWS_COUNTER_RIGHT");
//-----------------------

$left = -(($pagenum - (int) ($NEWS_COUNTER_CENTER / 2) - 1) - $NEWS_COUNTER_LEFT);
$right = - $countPages + $NEWS_COUNTER_RIGHT + ($pagenum + (int) ($NEWS_COUNTER_CENTER / 2) + 1);

if ($left >= 0 && $right >= 0 && $countPages > 0) {
//--центральный массив сливается с левым
//--центральный массив сливается с правым
//--создаем только 1 массив
//--centerIndexes
    $centerIndexes = array();
    for ($i = 1; $i <= $countPages; $i++) {
        $centerIndexes[] = $i;
    }
    $sm->assign("centerIndexes", $centerIndexes);
//--------------------------------------
} elseif ($left >= 0 && $right < 0 && $countPages > 0) {
//--центральный массив сливается с левым
//--создаем только 2 массива
//--leftIndexes
//--rightIndexes
    $leftIndexes = array();
    $rightIndexes = array();
    for ($i = 1; $i <= ($NEWS_COUNTER_LEFT + $NEWS_COUNTER_CENTER); $i++) {
        $leftIndexes[] = $i;
    }
    $endIndex = $i;
    for ($i = $countPages - $NEWS_COUNTER_RIGHT + 1; $i <= $countPages; $i++) {
        if($i > 0 && $i > $endIndex) {
            $rightIndexes[] = $i;
        }
    }
    $sm->assign("leftIndexes", $leftIndexes);
    $sm->assign("rightIndexes", $rightIndexes);
//---------------------------------------
} elseif ($left < 0 && $right >= 0 && $countPages > 0) {
//--центральный массив сливается с правым
//--создаем только 2 массива
//--leftIndexes
//--rightIndexes
    $leftIndexes = array();
    $rightIndexes = array();
    for ($i = 1; $i <= $NEWS_COUNTER_LEFT; $i++) {
        $leftIndexes[] = $i;
    }
    $endIndex = $i;
    for ($i = $countPages - $NEWS_COUNTER_RIGHT - $NEWS_COUNTER_CENTER; $i <= $countPages; $i++) {
        if($i > 0 && $i > $endIndex) {
            $rightIndexes[] = $i;
        }
    }
    $sm->assign("leftIndexes", $leftIndexes);
    $sm->assign("rightIndexes", $rightIndexes);
//---------------------------------------
} elseif($countPages > 0) {
//--центральный массив ни с кем не сливается
//--создаем 3 массива
//--leftIndexes
//--centerIndexes
//--rightIndexes
    $leftIndexes = array();
    $centerIndexes = array();
    $rightIndexes = array();
    for ($i = 1; $i <= $NEWS_COUNTER_LEFT; $i++) {
        $leftIndexes[] = $i;
    }
    $endIndex = $i;
    for ($i = $pagenum - (int) ($NEWS_COUNTER_CENTER / 2); $i <= $pagenum + (int) ($NEWS_COUNTER_CENTER / 2); $i++) {
        if($i > 0 && $i > $endIndex) {
            $centerIndexes[] = $i;
        }
    }
    $endIndex = $i;
    for ($i = $countPages - $NEWS_COUNTER_RIGHT + 1; $i <= $countPages; $i++) {
        if($i > 0 && $i > $endIndex) {
            $rightIndexes[] = $i;
        }
    }
    $sm->assign("leftIndexes", $leftIndexes);
    $sm->assign("centerIndexes", $centerIndexes);
    $sm->assign("rightIndexes", $rightIndexes);
//---------------------------------------
}

$db->dbq("
            Select
                newid as newid,
                caption as caption,
                maintext as maintext,
                DATE_FORMAT(postdate, \"%d %M %Y, %H:%i\") as postdate,
                author as author,
                archiveid as archiveid,
                tags as tags,
                position as position,
                (
                    Select
                        Count(*)
                    From
                        comments
                    Where
                        newid = news.newid
                ) as countComments
            From
                news
            Order By
                position DESC
            Limit
                " . ($pagenum - 1) * $NEWS_PER_PAGE . ",
                " . $NEWS_PER_PAGE . "
        ");

$news = array();
while ($arr = $db->assoc()) {
    $matches = array();
    preg_match("'\[img=\"?([^\]]*)\"?\][\s]*(.*)[\s]*\[/img\]'iu", $arr["maintext"], $matches);

    $arr["image"] = array();

    if ($matches[1] == "preview") {
        $arr["image"]["url"] = $matches[2];

        if ($matches[1] != "") {
            $type = exif_imagetype($curRealDir . $matches[2]);
            switch ($type) {
                case 1:
                    $image = imagecreatefromgif($curRealDir . $matches[2]);
                    $arr["image"]["width"] = imagesx($image);
                    $arr["image"]["height"] = imagesy($image);
                    imagedestroy($image);
                    break;
                case 2:
                    $image = imagecreatefromjpeg($curRealDir . $matches[2]);
                    $arr["image"]["width"] = imagesx($image);
                    $arr["image"]["height"] = imagesy($image);
                    imagedestroy($image);
                    break;
                case 3:
                    $image = imagecreatefrompng($curRealDir . $matches[2]);
                    $arr["image"]["width"] = imagesx($image);
                    $arr["image"]["height"] = imagesy($image);
                    imagedestroy($image);
                    break;
                default:
                    $arr["image"]["width"] = 0;
                    $arr["image"]["height"] = 0;
                    break;
            }
        }
    }

    $arr["maintext"] = bbCodeClear($arr["maintext"]);
    if (mb_strlen($arr["maintext"]) > $NEWS_MAX_LEN_PREVIEW) {
        $arr["maintext"] = mb_substr($arr["maintext"], 0, $NEWS_MAX_LEN_PREVIEW) . "...";
    }
    $arr["tags"] = json_decode($arr["tags"], true);
    $arr = stripRecursive($arr);
    $news[] = $arr;
}

$sm->assign("news", $news);

$sm->assign("design", "http://" . DOMEN_NAME . "/" . $sm->template_dir);
$sm->assign("displayedHtml", "index.html");
$sm->display("index.html");
?>
